﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace EBA.Ex
{
    public static class StringEx
    {
        static IFormatProvider _DefaultFormatProvider;
        public static IFormatProvider DefaultFormatProvider
        {
            get
            {
                if (_DefaultFormatProvider == null)
                {
                    _DefaultFormatProvider = Thread.CurrentThread.CurrentCulture;
                }
                return _DefaultFormatProvider;
            }
            set
            {
                _DefaultFormatProvider = value;
            }
        }
        static StringEx()
        {
            
        }

        public static bool HasValue(this string source)
        {
            return !string.IsNullOrWhiteSpace(source);
        }

        public static T ConvertTo<T>(this string source, IFormatProvider formatProvider = null)
        {
            return source.ConvertTo<T>(default(T), formatProvider);
        }

        public static T ConvertTo<T>(this string source, T defaultValue, IFormatProvider formatProvider=null)
        {
            if (source == null)
            {
                return defaultValue == null ? default(T) : defaultValue;
            }

            try
            {
                if (typeof(T) == typeof(bool) || typeof(T) == typeof(Boolean))
                {
                    return (T)((source == "True" || source == "true" || source == "1") ? (object)true : (object)false);
                }
                else
                {
                    if (formatProvider == null)
                    {
                        formatProvider = StringEx.DefaultFormatProvider;
                    }
                    return (T)Convert.ChangeType(source, typeof(T), formatProvider);
                }
            }
            catch
            {
                return defaultValue;
            }
        }

        public static Nullable<T> ConvertToNullable<T>(this string source, IFormatProvider formatProvider = null) where T : struct
        {
            if (source == null)
            {
                return null;
            }

            try
            {
                return (T)Convert.ChangeType(source, typeof(T),formatProvider);
            }
            catch
            {
                return null;
            }
        }

        public static string Fix(this string source, int length, char separator = '0')
        {
            var len = source.Length;
            if (len > length)
            {
                return source.Substring(0, length);
            }
            else if (len == length)
            {
                return source;
            }
            else
            {
                return source.PadRight(length, separator);
            }
        }



    }
}
